<script lang="ts" setup>
import { useRouter } from 'vue-router';

import { WorkbenchHeader } from '@vben/common-ui';
import { preferences } from '@vben/preferences';
import { useUserStore } from '@vben/stores';
import { openWindow } from '@vben/utils';
import { $t } from '@vben/locales';
import { message } from 'ant-design-vue';

import { postHooksSync } from '#/api/admin/hooks';
import { deleteSettingCache } from '#/api/admin/setting';
import { postUserActionsSync } from '#/api/user/actions';

import Navigation from './workspace-navigation.vue';
import VersionInfo from './workspace-versionInfo.vue';

const userStore = useUserStore();

const router = useRouter();

const items = [
  {
    click: '',
    icon: 'ri:settings-5-line',
    title: $t('admin.websiteSettings'),
    url: '/admin/setting/site',
    color: '#007BFF',
  },
  {
    click: '',
    icon: 'ri:t-shirt-line',
    title: $t('admin.templateManagement'),
    url: '/admin/theme',
    color: '#ADD8E6',
  },
  {
    click: '',
    icon: 'ri:slideshow-4-line',
    title: $t('admin.slideManagement'),
    url: '/admin/slide',
    color: '#87CEEB',
  },
  {
    click: '',
    icon: 'ri:navigation-line',
    title: $t('admin.navigationManagement'),
    url: '/admin/nav',
    color: '#FF7F50',
  },
  {
    click: '',
    icon: 'ri:links-line',
    title: $t('admin.friendLinks'),
    url: '/admin/link',
    color: '#FF1493',
  },
  {
    icon: 'ri:recycle-line',
    title: $t('admin.recycleBin'),
    url: '/admin/recyclebin/index',
    color: '#FFD700',
  },
  {
    icon: 'ri:file-list-3-line',
    title: $t('admin.resourceManagement'),
    url: '/user/adminasset/index',
    color: '#FFA500',
  },
  {
    click: 'handleClearCache',
    icon: 'ri:delete-bin-3-line',
    title: $t('admin.clearCache'),
    url: '',
    color: '#FFB6C1',
  },
];


// 清除缓存
const handleClearCache = async () => {
  await deleteSettingCache();
  message.success('成功清理缓存,等待刷新...', 2, () => {
    location.reload();
  });
};

// 用户操作同步
const handleUserActionsSync = async () => {
  const { msg } = await postUserActionsSync();
  message.success(msg);
};

// 用户操作同步
const handleHooksSync = async () => {
  const { msg } = await postHooksSync();
  message.success(msg);
};

// 这是一个示例方法，实际项目中需要根据实际情况进行调整
// This is a sample method, adjust according to the actual project requirements
function navTo(nav: {
  click: 'handleClearCache' | 'handleHooksSync' | 'handleUserActionsSync';
  color: string;
  icon: string;
  title: string;
  url: string;
}) {
  if (nav.url?.startsWith('http')) {
    openWindow(nav.url);
    return;
  }
  if (nav.url?.startsWith('/')) {
    router.push(nav.url).catch((error) => {
      console.error('Navigation failed:', error);
    });
  } else {
    console.warn(`Unknown URL for navigation item: ${nav.title} -> ${nav.url}`);
  }
  if (nav.click) {
    switch (nav.click) {
      case 'handleClearCache': {
        handleClearCache();
        break;
      }
      case 'handleHooksSync': {
        handleHooksSync();
        break;
      }
      case 'handleUserActionsSync': {
        handleUserActionsSync();
        break;
      }
      default: {
        break;
      }
    }
  }
}

const handleTips = () => {
  const hour = new Date().getHours();
  const realName =
    userStore.userInfo?.user_nickname && userStore.userInfo.user_nickname
      ? userStore.userInfo?.user_nickname
      : (userStore.userInfo?.user_login ?? '游客');

  const greetings: { message: string; range: any }[] = [
    { range: [0, 8], message: $t('admin.morningGreeting', { name: realName }) },
    { range: [8, 11], message:  $t('admin.forenoonGreeting', { name: realName })},
    {
      range: [11, 13],
      message: $t('admin.noonGreeting', { name: realName }),
    },
    {
      range: [13, 18],
      message: $t('admin.afternoonGreeting', { name: realName }),
    },
    {
      range: [18, 24],
      message: $t('admin.eveningGreeting', { name: realName }),
    },
  ];

  const greeting = greetings.find(({ range }) => {
    // 确保 range 不为 undefined
    if (range) {
      return hour >= range[0] && hour < range[1];
    }
    return false;
  });

  return greeting?.message || $t('admin.defaultGreeting', { name: realName });
};
</script>

<template>
  <div class="p-5">
    <WorkbenchHeader
      :avatar="userStore.userInfo?.avatar || preferences.app.defaultAvatar"
    >
      <template #title> {{ handleTips() }} </template>
      <template #description>
        {{ userStore.userInfo?.signature || $t('admin.keepWordsSecret') }}
      </template>
    </WorkbenchHeader>

    <div class="mt-5 flex flex-col">
      <div class="w-full">
        <Navigation :items="items" @click="navTo" />
      </div>
      <div class="mt-5 w-full">
        <VersionInfo />
      </div>
    </div>
  </div>
</template>
